# -*- coding:utf-8 -*-
"""
@File   : Ding_send.py
@Time : 2024/12/27 16:08
@Author: Wangwc
@Describe: 钉钉消息发送相关功能，用于发送测试报告结果到钉钉
"""
import base64
import os
import urllib
import requests
import time
# import hmac
# import hashlib
# import xml.etree.ElementTree as ET
#
# from loguru import logger
# from config.path import xml_report
# from business.SystemApi import SystemApi
# from utils.login import Login
#
# config_name = 'user.ini'
# login = Login(config_name=config_name)
# token = login.login()
# system = SystemApi(token,configname=config_name)
#
# report_url = "http://192.168.75.105:8000/allure_report"
#

#
# def generate_signature(secret):
#     """
#     根据给定的secret生成钉钉机器人请求的签名
#     """
#     timestamp = round(time.time() * 1000)
#     logger.debug(f"生成的时间戳：{timestamp}")
#     string_to_sign = f'{timestamp}\n{secret}'
#     string_to_sign_enc = string_to_sign.encode('utf-8')
#     secret_enc = secret.encode('utf-8')
#     hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
#     return urllib.parse.quote_plus(base64.b64encode(hmac_code)), timestamp
#
#
# def build_request_url(access_token):
#     """
#     构建发送钉钉消息的请求URL
#     """
#     # return f"https://oapi.dingtalk.com/robot/send?access_token={access_token}&timestamp={timestamp}&sign={sign}"
#     return f"https://oapi.dingtalk.com/robot/send?access_token={access_token}"
#
#
# def build_request_headers():
#     """
#     构建发送钉钉消息的请求头
#     """
#     return {
#         "Content-Type": "application/json"
#     }
#
#
# def build_request_data(tests, failures, skipped,errors):
#     """
#     根据测试结果构建发送钉钉消息的请求数据（以markdown格式），优化显示格式。
#     """
#     success = int(tests) - int(failures) -int(skipped) - int(errors)
#     success_rate = int(tests) - int(failures) - int(errors)
#     success_rate_text = round((success_rate * 100 / int(tests)), 2)
#     success_rate_color = "green" if success_rate_text == 100.0 else "red"
#     success_rate = f'<font color="{success_rate_color}">{success_rate_text:.2f}%</font>'
#     firmware_version = system.get_firmware_version()
#
#     message_content = {
#         "msgtype": "markdown",
#         "markdown": {
#             "title": "NAS接口自动化",
#             "text": "## 存储管理器&控制面板接口自动化\n"
#                     "#### 测试概述\n"
#                     "- 当前固件版本: " + str(firmware_version) + "\n"
#                     "- 接口用例总数: " + str(tests) + "\n"
#                     "- 成功用例数: " + str(success) + "\n"
#                     "- 失败用例数: " + str(failures) + "\n"
#                     "- 跳过用例数: " + str(skipped) + "\n"
#                     "- 错误用例数: " + str(errors) + "\n"
#                     "- 用例成功率: " + str(success_rate) + "\n"
#                     "#### 相关链接\n"
#                     "- 报告地址: " + report_url + "\n"
#         }
#     }
#
#     return message_content
#
# def send_ding_talk_message(access_token):
#     """
#     发送钉钉消息的主函数，整合各步骤完成消息发送，并处理响应结果
#     """
#     try:
#         logger.info("开始发送钉钉消息")
#         # sign, timestamp = generate_signature(secret)
#         url = build_request_url(access_token)
#         headers = build_request_headers()
#         # 解析报告文件获取测试结果数据，这里添加对REPORT_PATH文件的校验逻辑
#         if not xml_report or not os.path.isfile(xml_report):
#             raise FileNotFoundError(f"报告文件 {xml_report} 不存在或不是合法文件")
#         tree = ET.parse(xml_report)
#         root = tree.getroot()
#         first_line_element = root[0]
#         tests = first_line_element.attrib.get("tests")
#         failures = first_line_element.attrib.get("failures")
#         skipped = first_line_element.attrib.get("skipped")
#         errors = first_line_element.attrib.get("errors")
#         message_content = build_request_data(tests, failures, skipped,errors)
#
#         data1={"liao":"廖总晚上好！！！"}
#         data = message_content
#
#         logger.debug(f"请求URL：{url}")
#         logger.debug(f"请求数据：{data}")
#
#         response = requests.post(url, headers=headers, json=data1)
#         logger.info(f"请求已发送，状态码：{response.status_code}")
#
#         response_data = response.json()
#         if response.status_code == 200 and response_data.get("errcode") == 0:
#             logger.info("钉钉消息发送成功")
#         else:
#             logger.error(f"钉钉消息发送失败，响应：{response_data}")
#             # 可以根据不同的errcode返回更详细的错误提示信息给调用者
#             raise requests.RequestException(f"钉钉消息发送失败，错误码: {response_data.get('errcode')}")
#
#         return response_data
#
#     except requests.RequestException as req_error:
#         logger.error(f"请求错误：{req_error}", exc_info=True)
#         raise
#     except FileNotFoundError as file_error:
#         logger.error(f"文件相关错误：{file_error}", exc_info=True)
#         raise
#     except Exception as e:
#         logger.error(f"发生未知错误：{e}", exc_info=True)
#         raise



def MytestSend(access_token):
    """
     f"https://oapi.dingtalk.com/robot/send?access_token={access_token}"
    :param accesToke:
    :return:
    """
    # timestamp=round(time.time() * 1000)

    url=f"https://oapi.dingtalk.com/robot/send?access_token={access_token}"
    print( url)
    data={"msgtype":"text",
          "text":{
              "content":"廖总晚上好"
          }
          }
    response=requests.post(url,json=data)
    print(response.json())




if __name__ == '__main__':


    # access_token = 'b07dda9bc888a2f7a898dce71c11a9e20f94671e8a7902db7431833dab248435'  # 测试部自动化机器人
    access_token ='a8de828acad5794875abd4c2eb2d0479f5fbcbd861c71a6ef906d2816a0fef4e'  # 测试部自动化机器人    SECeef3717d36326fd6fb23557fd2f442665e27bbbc0768d1550b7ca263d719b530
    # access_token = '99c5fd91d473df2c2e262392327230f38dcd7851a64029d267ef1181fb3045d3'   # 自己调试的机器人
    # secret = 'SEC1cd356b0ef6ae41f81f490eb05ff6630a84dc3e7f0dd373a13b6b45d5185e17a'
    # send_ding_talk_message(access_token)
    MytestSend(access_token)
